<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alex008 电商搜索系统 - ElasticSearch 演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(45deg, #ff6b6b, #ee5a52);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .search-section {
            padding: 30px;
            background: #f8f9fa;
        }

        .search-box {
            position: relative;
            margin-bottom: 20px;
        }

        .search-input {
            width: 100%;
            padding: 15px 50px 15px 20px;
            font-size: 18px;
            border: 2px solid #e0e0e0;
            border-radius: 25px;
            outline: none;
            transition: all 0.3s ease;
        }

        .search-input:focus {
            border-color: #667eea;
            box-shadow: 0 0 20px rgba(102, 126, 234, 0.3);
        }

        .search-btn {
            position: absolute;
            right: 5px;
            top: 50%;
            transform: translateY(-50%);
            background: #667eea;
            color: white;
            border: none;
            border-radius: 20px;
            padding: 10px 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .search-btn:hover {
            background: #5a67d8;
            transform: translateY(-50%) scale(1.05);
        }

        .suggestions {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 10px;
            max-height: 200px;
            overflow-y: auto;
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            z-index: 1000;
            display: none;
        }

        .suggestion-item {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 1px solid #f0f0f0;
            transition: background 0.2s ease;
        }

        .suggestion-item:hover {
            background: #f8f9fa;
        }

        .filters {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-label {
            font-weight: bold;
            margin-bottom: 5px;
            color: #333;
        }

        .filter-input {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .quick-search {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 20px;
        }

        .quick-btn {
            background: #fff;
            border: 2px solid #667eea;
            color: #667eea;
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
        }

        .quick-btn:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
        }

        .results-section {
            padding: 0 30px 30px;
        }

        .results-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding: 15px 0;
            border-bottom: 2px solid #e0e0e0;
        }

        .results-count {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }

        .sort-controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .sort-select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background: white;
        }

        .products-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
        }

        .product-card {
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 15px;
            padding: 20px;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 30px rgba(0,0,0,0.1);
            border-color: #667eea;
        }

        .product-name {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
            line-height: 1.4;
        }

        .product-description {
            color: #666;
            font-size: 14px;
            margin-bottom: 15px;
            line-height: 1.5;
        }

        .product-meta {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 15px;
        }

        .meta-item {
            font-size: 12px;
            color: #888;
        }

        .meta-value {
            font-weight: bold;
            color: #333;
        }

        .product-price {
            font-size: 24px;
            font-weight: bold;
            color: #ff6b6b;
            margin-bottom: 10px;
        }

        .product-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }

        .tag {
            background: #667eea;
            color: white;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 10px;
        }

        .loading {
            text-align: center;
            padding: 50px;
            font-size: 18px;
            color: #666;
        }

        .no-results {
            text-align: center;
            padding: 50px;
            color: #666;
        }

        .no-results h3 {
            margin-bottom: 10px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 30px;
        }

        .page-btn {
            background: white;
            border: 1px solid #ddd;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .page-btn:hover {
            background: #667eea;
            color: white;
        }

        .page-btn.active {
            background: #667eea;
            color: white;
        }

        .page-btn:disabled {
            background: #f0f0f0;
            color: #ccc;
            cursor: not-allowed;
        }

        .init-section {
            text-align: center;
            padding: 20px;
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .init-btn {
            background: #f39c12;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        .init-btn:hover {
            background: #e67e22;
            transform: scale(1.05);
        }

        .highlight {
            background: yellow;
            font-weight: bold;
        }

        .stats-section {
            background: #e8f4f8;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
        }

        .stat-item {
            text-align: center;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-size: 24px;
            font-weight: bold;
            color: #667eea;
        }

        .stat-label {
            font-size: 14px;
            color: #666;
            margin-top: 5px;
        }

        @media (max-width: 768px) {
            .filters {
                grid-template-columns: 1fr;
            }

            .products-grid {
                grid-template-columns: 1fr;
            }

            .sort-controls {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>🔍 Alex008 电商搜索系统</h1>
        <p>体验 ElasticSearch 的强大搜索能力</p>
    </div>

    <!-- 初始化数据区域 -->
    <div class="init-section">
        <h3>📋 首次使用请先初始化测试数据</h3>
        <button class="init-btn" onclick="initData()">初始化测试数据</button>
        <div id="initResult" style="margin-top: 10px;"></div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section" id="statsSection" style="display: none;">
        <h3 style="margin-bottom: 15px;">📊 数据统计</h3>
        <div class="stats-grid" id="statsGrid">
            <!-- 统计数据将在这里显示 -->
        </div>
    </div>

    <div class="search-section">
        <!-- 搜索框 -->
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput"
                   placeholder="🔍 输入商品名称，如：iPhone、华为、笔记本..."
                   onkeyup="handleSearchInput(event)">
            <button class="search-btn" onclick="performSearch()">搜索</button>
            <div class="suggestions" id="suggestions"></div>
        </div>

        <!-- 快速搜索按钮 -->
        <div class="quick-search">
            <span style="font-weight: bold; margin-right: 10px;">🔥 热门搜索：</span>
            <button class="quick-btn" onclick="quickSearch('iPhone')">iPhone</button>
            <button class="quick-btn" onclick="quickSearch('华为')">华为</button>
            <button class="quick-btn" onclick="quickSearch('笔记本')">笔记本</button>
            <button class="quick-btn" onclick="quickSearch('Pro')">Pro</button>
            <button class="quick-btn" onclick="quickSearch('降噪')">降噪</button>
            <button class="quick-btn" onclick="quickSearch('5G')">5G</button>
        </div>

        <!-- 高级筛选 -->
        <div class="filters">
            <div class="filter-group">
                <label class="filter-label">📱 分类</label>
                <select class="filter-input" id="categoryFilter">
                    <option value="">全部分类</option>
                    <option value="手机">手机</option>
                    <option value="笔记本">笔记本</option>
                    <option value="耳机">耳机</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">🏷️ 品牌</label>
                <select class="filter-input" id="brandFilter">
                    <option value="">全部品牌</option>
                    <option value="Apple">Apple</option>
                    <option value="Huawei">华为</option>
                    <option value="Xiaomi">小米</option>
                    <option value="Lenovo">联想</option>
                    <option value="Dell">戴尔</option>
                    <option value="Sony">索尼</option>
                </select>
            </div>
            <div class="filter-group">
                <label class="filter-label">💰 最低价格</label>
                <input type="number" class="filter-input" id="minPrice" placeholder="如：1000">
            </div>
            <div class="filter-group">
                <label class="filter-label">💰 最高价格</label>
                <input type="number" class="filter-input" id="maxPrice" placeholder="如：10000">
            </div>
        </div>
    </div>

    <div class="results-section">
        <!-- 搜索结果头部 -->
        <div class="results-header" id="resultsHeader" style="display: none;">
            <div class="results-count" id="resultsCount">搜索结果</div>
            <div class="sort-controls">
                <label>排序方式：</label>
                <select class="sort-select" id="sortBy">
                    <option value="salesCount">销量</option>
                    <option value="price">价格</option>
                    <option value="rating">评分</option>
                </select>
                <select class="sort-select" id="sortOrder">
                    <option value="desc">降序</option>
                    <option value="asc">升序</option>
                </select>
                <button class="search-btn" onclick="performAdvancedSearch()" style="position: static; transform: none;">应用排序</button>
            </div>
        </div>

        <!-- 加载状态 -->
        <div class="loading" id="loading" style="display: none;">
            🔄 正在搜索中...
        </div>

        <!-- 搜索结果网格 -->
        <div class="products-grid" id="productsGrid">
            <!-- 产品卡片将在这里显示 -->
        </div>

        <!-- 无结果状态 -->
        <div class="no-results" id="noResults" style="display: none;">
            <h3>😅 没有找到相关商品</h3>
            <p>试试搜索其他关键词，或者调整筛选条件</p>
        </div>

        <!-- 分页 -->
        <div class="pagination" id="pagination" style="display: none;">
            <!-- 分页按钮将在这里显示 -->
        </div>
    </div>
</div>

<script>
    // 全局变量
    let currentPage = 0;
    let currentKeyword = '';
    let isHighlightMode = false;

    // 初始化数据
    async function initData() {
        const initBtn = document.querySelector('.init-btn');
        const initResult = document.getElementById('initResult');

        initBtn.disabled = true;
        initBtn.textContent = '正在初始化...';

        try {
            const response = await fetch('/api/products/init-data');
            const result = await response.json();

            if (result.status === 'success') {
                initResult.innerHTML = '<div style="color: green;">✅ ' + result.message + '</div>';
                loadStats();
                setTimeout(() => {
                    document.getElementById('statsSection').style.display = 'block';
                }, 500);
            } else {
                initResult.innerHTML = '<div style="color: red;">❌ ' + result.message + '</div>';
            }
        } catch (error) {
            initResult.innerHTML = '<div style="color: red;">❌ 初始化失败：' + error.message + '</div>';
        } finally {
            initBtn.disabled = false;
            initBtn.textContent = '初始化测试数据';
        }
    }

    // 加载统计信息
    async function loadStats() {
        try {
            const response = await fetch('/api/products/stats');
            const stats = await response.json();

            const statsGrid = document.getElementById('statsGrid');
            statsGrid.innerHTML = `
                    <div class="stat-item">
                        <div class="stat-number">${stats.totalProducts}</div>
                        <div class="stat-label">商品总数</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">6</div>
                        <div class="stat-label">品牌数量</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">3</div>
                        <div class="stat-label">商品分类</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number">毫秒级</div>
                        <div class="stat-label">搜索速度</div>
                    </div>
                `;
        } catch (error) {
            console.error('加载统计信息失败:', error);
        }
    }

    // 处理搜索输入
    function handleSearchInput(event) {
        const keyword = event.target.value.trim();

        if (event.key === 'Enter') {
            performSearch();
            return;
        }

        // 搜索建议
        if (keyword.length >= 2) {
            getSuggestions(keyword);
        } else {
            hideSuggestions();
        }
    }

    // 获取搜索建议
    async function getSuggestions(prefix) {
        try {
            const response = await fetch(`/api/products/suggestions?prefix=${encodeURIComponent(prefix)}`);
            const suggestions = await response.json();

            const suggestionsDiv = document.getElementById('suggestions');

            if (suggestions.length > 0) {
                suggestionsDiv.innerHTML = suggestions.map(suggestion =>
                    `<div class="suggestion-item" onclick="selectSuggestion('${suggestion}')">${suggestion}</div>`
                ).join('');
                suggestionsDiv.style.display = 'block';
            } else {
                hideSuggestions();
            }
        } catch (error) {
            console.error('获取搜索建议失败:', error);
            hideSuggestions();
        }
    }

    // 选择建议
    function selectSuggestion(suggestion) {
        document.getElementById('searchInput').value = suggestion;
        hideSuggestions();
        performSearch();
    }

    // 隐藏搜索建议
    function hideSuggestions() {
        document.getElementById('suggestions').style.display = 'none';
    }

    // 快速搜索
    function quickSearch(keyword) {
        document.getElementById('searchInput').value = keyword;
        performSearch();
    }

    // 执行简单搜索
    async function performSearch() {
        const keyword = document.getElementById('searchInput').value.trim();
        if (!keyword) {
            alert('请输入搜索关键词');
            return;
        }

        currentKeyword = keyword;
        currentPage = 0;
        isHighlightMode = true;

        showLoading();
        hideSuggestions();

        try {
            const response = await fetch(`/api/products/search-highlight?keyword=${encodeURIComponent(keyword)}`);
            const results = await response.json();

            displayHighlightResults(results, keyword);
            document.getElementById('resultsHeader').style.display = 'flex';
            document.getElementById('resultsCount').textContent = `找到 ${results.length} 个相关商品 (关键词: "${keyword}")`;

        } catch (error) {
            console.error('搜索失败:', error);
            showNoResults();
        } finally {
            hideLoading();
        }
    }

    // 执行高级搜索
    async function performAdvancedSearch() {
        const keyword = document.getElementById('searchInput').value.trim();
        const category = document.getElementById('categoryFilter').value;
        const brand = document.getElementById('brandFilter').value;
        const minPrice = document.getElementById('minPrice').value;
        const maxPrice = document.getElementById('maxPrice').value;
        const sortBy = document.getElementById('sortBy').value;
        const sortOrder = document.getElementById('sortOrder').value;

        currentKeyword = keyword;
        isHighlightMode = false;

        showLoading();

        try {
            const params = new URLSearchParams();
            if (keyword) params.append('keyword', keyword);
            if (category) params.append('category', category);
            if (brand) params.append('brand', brand);
            if (minPrice) params.append('minPrice', minPrice);
            if (maxPrice) params.append('maxPrice', maxPrice);
            params.append('sortBy', sortBy);
            params.append('sortOrder', sortOrder);
            params.append('page', currentPage);
            params.append('size', 10);

            const response = await fetch(`/api/products/advanced-search?${params}`);
            const result = await response.json();

            if (result.error) {
                throw new Error(result.error);
            }

            displayAdvancedResults(result);
            document.getElementById('resultsHeader').style.display = 'flex';

            // 构建筛选条件描述
            let filterDesc = [];
            if (keyword) filterDesc.push(`关键词: "${keyword}"`);
            if (category) filterDesc.push(`分类: ${category}`);
            if (brand) filterDesc.push(`品牌: ${brand}`);
            if (minPrice || maxPrice) {
                filterDesc.push(`价格: ${minPrice || '0'} - ${maxPrice || '∞'}`);
            }

            document.getElementById('resultsCount').textContent =
                `找到 ${result.totalElements} 个商品 ${filterDesc.length > 0 ? '(' + filterDesc.join(', ') + ')' : ''}`;

            // 显示分页
            displayPagination(result);

        } catch (error) {
            console.error('高级搜索失败:', error);
            showNoResults();
        } finally {
            hideLoading();
        }
    }

    // 显示高亮搜索结果
    function displayHighlightResults(results, keyword) {
        const grid = document.getElementById('productsGrid');

        if (results.length === 0) {
            showNoResults();
            return;
        }

        grid.innerHTML = results.map(item => {
            const product = item.product;
            const highlights = item.highlights;

            // 使用高亮的名称和描述
            const highlightedName = highlights.productName && highlights.productName.length > 0
                ? highlights.productName[0]
                : product.productName;

            const highlightedDesc = highlights.description && highlights.description.length > 0
                ? highlights.description[0]
                : product.description;

            return createProductCard(product, highlightedName, highlightedDesc, true);
        }).join('');

        document.getElementById('noResults').style.display = 'none';
        document.getElementById('pagination').style.display = 'none';
    }

    // 显示高级搜索结果
    function displayAdvancedResults(result) {
        const grid = document.getElementById('productsGrid');

        if (result.products.length === 0) {
            showNoResults();
            return;
        }

        grid.innerHTML = result.products.map(product =>
            createProductCard(product, product.productName, product.description, false)
        ).join('');

        document.getElementById('noResults').style.display = 'none';
    }

    // 创建商品卡片
    function createProductCard(product, displayName, displayDesc, isHighlight) {
        const tags = product.tags ? product.tags.map(tag =>
            `<span class="tag">${tag}</span>`
        ).join('') : '';

        return `
                <div class="product-card">
                    <div class="product-name">${displayName}</div>
                    <div class="product-description">${displayDesc}</div>
                    <div class="product-meta">
                        <div class="meta-item">
                            <div class="meta-value">${product.brand}</div>
                            <div>品牌</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-value">${product.category}</div>
                            <div>分类</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-value">${product.salesCount?.toLocaleString() || 0}</div>
                            <div>销量</div>
                        </div>
                        <div class="meta-item">
                            <div class="meta-value">⭐ ${product.rating || 0}</div>
                            <div>评分</div>
                        </div>
                    </div>
                    <div class="product-price">¥${product.price}</div>
                    <div class="product-tags">${tags}</div>
                    ${isHighlight ? '<div style="margin-top: 10px; font-size: 12px; color: #ff6b6b;">🎯 智能匹配</div>' : ''}
                </div>
            `;
    }

    // 显示分页
    function displayPagination(result) {
        const pagination = document.getElementById('pagination');

        if (result.totalPages <= 1) {
            pagination.style.display = 'none';
            return;
        }

        let paginationHTML = '';

        // 上一页按钮
        paginationHTML += `
                <button class="page-btn" ${currentPage === 0 ? 'disabled' : ''} onclick="goToPage(${currentPage - 1})">
                    « 上一页
                </button>
            `;

        // 页码按钮
        const startPage = Math.max(0, currentPage - 2);
        const endPage = Math.min(result.totalPages - 1, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            paginationHTML += `
                    <button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="goToPage(${i})">
                        ${i + 1}
                    </button>
                `;
        }

        // 下一页按钮
        paginationHTML += `
                <button class="page-btn" ${currentPage >= result.totalPages - 1 ? 'disabled' : ''} onclick="goToPage(${currentPage + 1})">
                    下一页 »
                </button>
            `;

        pagination.innerHTML = paginationHTML;
        pagination.style.display = 'flex';
    }

    // 跳转到指定页
    function goToPage(page) {
        currentPage = page;
        if (isHighlightMode && currentKeyword) {
            performSearch();
        } else {
            performAdvancedSearch();
        }
    }

    // 显示加载状态
    function showLoading() {
        document.getElementById('loading').style.display = 'block';
        document.getElementById('productsGrid').innerHTML = '';
        document.getElementById('noResults').style.display = 'none';
    }

    // 隐藏加载状态
    function hideLoading() {
        document.getElementById('loading').style.display = 'none';
    }

    // 显示无结果状态
    function showNoResults() {
        document.getElementById('productsGrid').innerHTML = '';
        document.getElementById('noResults').style.display = 'block';
        document.getElementById('pagination').style.display = 'none';
        document.getElementById('resultsHeader').style.display = 'none';
    }

    // 点击其他地方隐藏搜索建议
    document.addEventListener('click', function(event) {
        if (!event.target.closest('.search-box')) {
            hideSuggestions();
        }
    });

    // 筛选条件变化时自动搜索
    document.getElementById('categoryFilter').addEventListener('change', function() {
        if (currentKeyword || this.value) {
            performAdvancedSearch();
        }
    });

    document.getElementById('brandFilter').addEventListener('change', function() {
        if (currentKeyword || this.value) {
            performAdvancedSearch();
        }
    });

    // 价格输入框失去焦点时搜索
    document.getElementById('minPrice').addEventListener('blur', function() {
        if (currentKeyword || this.value) {
            setTimeout(() => performAdvancedSearch(), 300);
        }
    });

    document.getElementById('maxPrice').addEventListener('blur', function() {
        if (currentKeyword || this.value) {
            setTimeout(() => performAdvancedSearch(), 300);
        }
    });

    // 页面加载完成后尝试加载统计信息
    window.addEventListener('load', function() {
        loadStats();
    });
</script>
</body>
</html>